package edu.zut.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

@WebServlet(name = "ServletDemo1", urlPatterns = "/demo1")
public class ServletDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取一个ServletContext对象   这个对象是全局唯一，被所有用户以及servlet对象共享的
//        ServletContext context1 = request.getServletContext();
        ServletContext context = this.getServletContext();
        //先去获取统计访问次数的计算器，如果获取到，我们直接+1，如果获取不到，直接设置一个
        Integer count = (Integer) context.getAttribute("count");
        if (count == null) {
            count = 1;
        } else {
            count++;
        }
        context.setAttribute("count", count);

        //获取上下文参数：
        String v = context.getInitParameter("key");
        System.out.println("v = " + v);
        //获取资源配置信息
        InputStream stream = context.getResourceAsStream("db.properties");
        Properties properties = new Properties();
        properties.load(stream);
        //根据key获取value
        String jdbc_name = properties.getProperty("jdbc.username");
        System.out.println("jdbc_name = " + jdbc_name);

        response.getWriter().write("访问次数：" + count);

    }
}
